﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using EvaluationSystem.DAO;
using System.Data;
using System.Text;
using EvaluationSystem.Exceptions;

namespace EvaluationSystem.ConfigurationPages.TabsPages
{
    public partial class TabsPage : System.Web.UI.Page
    {
        TabsManager tabsManager = new TabsManager();
        StaffManager staffManager = new StaffManager();
        TextField txtTabName = new TextField();
        DropDownField ddfRole = new DropDownField();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Utility.IsLogin(this.Page))
            {
#if !DEBUG
                Response.Redirect("../Default.aspx");
#endif
            }
        }

        protected void Store_RefreshData(object sender, StoreRefreshDataEventArgs e)
        {
            this.objectDataSource.SelectParameters[Constants.Start].DefaultValue = e.Start.ToString();
            this.objectDataSource.SelectParameters[Constants.Limit].DefaultValue = e.Limit.ToString();
            this.objectDataSource.SelectParameters[Constants.Sort].DefaultValue = e.Sort;
            this.objectDataSource.SelectParameters[Constants.Dir].DefaultValue = e.Dir.ToString();

            this.store.DataBind();
        }

        protected void ObjectDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            (this.store.Proxy[0] as PageProxy).Total = (int)e.OutputParameters["count"];
        }

        public List<Tabs> GetTabsFilter(int start, int limit, string sort, string dir, out int count)
        {
            DataTable dt = tabsManager.GetAllTabs();
            IEnumerable<DataRow> rows = null;
            if (start >= 0 && limit > 0)
            {
                rows = dt.Select().Skip(start).Take(limit);
            }

            count = tabsManager.GetTabsCount(this.Page);
            List<Tabs> result = new List<Tabs>(limit);
            foreach (DataRow row in rows)
            {
                result.Add(new Tabs
                { 
                    Id = (int)row["Id"],
                    TabName = (string)row["TabName"],
                    RoleName = (string)row["RoleName"],
                });
            }
            return result;
        }

        [DirectMethod]
        public void DeleteTab(string tabId)
        {
            bool isSuccess = tabsManager.DeleteTabByTabId(tabId);
            if (isSuccess)
            {
                //update the row count so that the paging works.
                tabsManager.GetTabsCount(this.Page, true);
                X.MessageBox.Alert(Constants.Noticfy, "删除成功.");
                gpTabs.Reload();
            }
            else
            {
                X.MessageBox.Alert(Constants.Noticfy, "删除异常，请重新尝试或联系开发人员.");
            }
        }

        [DirectMethod]
        public void EditTab(string id, string tabName, string roleName)
        {
            Window win = CreateWindow(id,roleName, tabName);
            win.Render(this.Form);
            win.Show();
        }

        private void InitRoles(TreePanel tpRole, DropDownField ddfRole, string selectedRoles)
        {
            StringBuilder sbToolTip = new StringBuilder();
            DataTable dt = staffManager.GetRoles();
            string[] selectRoles = null;
            selectRoles = selectedRoles.Split(Constants.SplitKey.ToCharArray());
            Ext.Net.TreeNode root = new Ext.Net.TreeNode();
            foreach (DataRow row in dt.Rows)
            {
                Ext.Net.TreeNode node = new Ext.Net.TreeNode(row[0].ToString(), row[1] as string, Icon.ArrowJoin);
                node.Checked = selectRoles == null || !selectRoles.Contains(node.Text) ? ThreeStateBool.False : ThreeStateBool.True;
                node.Leaf = true;
                root.Nodes.Add(node);
                if (node.Checked == ThreeStateBool.True)
                {
                    SetGroupDisplayValue(row[1] as string, ddfRole);
                }
                sbToolTip.Append(String.Format("<table><tr><td width=70>{0}</td><td width=200>{1}</td></tr></table>", row[1] as string, row[2] as string));

            }
            tpRole.Root.Add(root);
            tooltipForRole.Html = sbToolTip.ToString();
        }

        private void SetGroupDisplayValue(string value, DropDownField ddfRole)
        {
            string theValue = ddfRole.Text;
            if (ddfRole.Text.Length > 0)
            {
                theValue += Constants.SplitKey;
            }
            theValue += value;
            ddfRole.Text = theValue;
        }

        private Window CreateWindow(string id, string roleName, string tab)
        {
            Window win = new Window()
            {
                Closable = true,
                Resizable = false,
                Height = 200,
                Icon = Icon.Application,
                Title = "修改页签",
                Draggable = true,
                Width = 350,
                Modal = true,
                Padding = 5,
                CloseAction = Ext.Net.CloseAction.Close,
                Layout = "AnchorLayout",
                ID = "TabsEditWindow"
            };
            win.Listeners.Close.Handler = "Ext.net.DirectMethods.Reload();";
            txtTabName = new TextField()
            {
                ID = "txtTabName",
                FieldLabel = "页签",
                AllowBlank = false,
                BlankText = "请输入页签",
                AnchorHorizontal = "100%"
                
            };
            win.Items.Add(txtTabName);
            ddfRole = new DropDownField()
            {
                AnchorHorizontal = "100%",
                TriggerIcon = TriggerIcon.SimpleArrowDown,
                FieldLabel = "角色",
                AllowBlank = false,
                BlankText = "请选角色.",
                ID = "ddfRole"
            };
            TreePanel tpRole = new TreePanel()
            {
                Title = "角色",
                Icon = Icon.Accept,
                Height = 300,
                UseArrows = true,
                AutoScroll = true,
                Animate = true,
                EnableDD = true,
                ContainerScroll = true,
                RootVisible = true,
                ID = "tpRole"
            };
            Ext.Net.Button button = new Ext.Net.Button{ Text = "Close"};
            button.Listeners.Click.Handler = "#{tpRole}.collapse();";
            tpRole.Buttons.Add(button);
            tpRole.Listeners.CheckChange.Handler = "this.dropDownField.setValue(getTasks(this), false);";
            tpRole.Icon = Icon.Accept;
            ddfRole.Component.Add(tpRole);
            
            ddfRole.Listeners.Expand.Handler = "this.component.getRootNode().expand(true);";
            ddfRole.Listeners.Expand.Single = true;
            win.Items.Add(ddfRole);
            Ext.Net.Button btnSave = new Ext.Net.Button()
            {
                ID = "btnSave",
                Text = "保存",
                Icon = Icon.Accept
            };
            btnSave.Listeners.Click.Handler = " if (!#{txtTabName}.validate() || !#{ddfRole}.validate()) { Ext.Msg.alert('Error','请填写必要内容.');return false; }";
            btnSave.Listeners.Click.Handler = "Ext.net.DirectMethods.btnSave_Click(" + id + ",#{txtTabName}.getValue(),#{ddfRole}.getText());";
            //btnSave.Click.DirectEvents.Click..Event += new ComponentDirectEvent.DirectEventHandler(btnSave_Click);
            btnSave.DirectEvents.Click.EventMask.ShowMask = true;
            btnSave.DirectEvents.Click.EventMask.Msg = "保存中...";
            btnSave.DirectEvents.Click.EventMask.MinDelay = 500;
            win.Buttons.Add(btnSave);

            Ext.Net.Button btnCancel = new Ext.Net.Button()
            {
                ID = "btnCancel",
                Text = "关闭",
                Icon = Icon.Decline
            };
            btnCancel.Listeners.Click.Handler = "#{TabsEditWindow}.close();";
            win.Buttons.Add(btnCancel);

            InitRoles(tpRole, ddfRole, roleName);
            txtTabName.Text = tab;

            return win;
        }

        [DirectMethod]
        public void Reload()
        {
            gpTabs.Reload();
        }

        [DirectMethod]
        public void btnSave_Click(string id,string tabName,string roleName)
        {
            try
            {
                bool isSuccess = tabsManager.UpdateTabById(id,tabName,roleName);
                if (isSuccess)
                {
                    X.MessageBox.Alert(Constants.Noticfy, "修改页签成功.").Show();

                }
                else
                {
                    X.MessageBox.Alert(Constants.Noticfy, "保存出错，请重新尝试或联系开发人员.").Show();
                }
            }
            catch (ExistTabException ex)
            {
                X.MessageBox.Alert(Constants.Noticfy, ex.Message).Show();
            }
        }
    }
}